import {
  allocatePageApi,
  addAllocateApi,
  editAllocateApi,
  delAllocateApi
} from '@/api/workflow/allocate'
import { Ref } from 'vue'
import { ProTableInst } from '@/components/pro-table/type'
import { PageRequest } from '@/api/types'
import { AllocateModel } from '@/api/model/allocate-model'
import { userInfo } from '~/types/user'
import { userInfoModel } from '@/api/model/userModel'
import dayjs from 'dayjs'

type Props = {
  handleType: Ref<'add' | 'edit' | 'check'>
  handleTag: Ref<string>
  allocateModalShow: Ref<boolean>
  allocateForm: Ref<Partial<AllocateModel>>
  proTableInst: Ref<ProTableInst | null>
  userInfo: Ref<userInfo<userInfoModel>>
  orgOptions: Ref<any>
}

export const useAllocateApi = ({
  handleType,
  handleTag,
  allocateModalShow,
  allocateForm,
  proTableInst,
  userInfo,
  orgOptions
}: Props) => {
  const confirmLoading = ref(false)

  // 获取调拨列表
  const fetchAllocatePage = async (
    pageRequest: PageRequest,
    queryParams: AllocateModel
  ) => {
    const res = await allocatePageApi({
      ...queryParams,
      orgId: userInfo.value.orgId,
      pageRequest
    })

    if (res.code === '0000') {
      return {
        data: res.data?.content,
        total: res.data?.total
      }
    }
  }

  // 新增or修改调拨
  const fetchAddOrEditAllocate = async () => {
    confirmLoading.value = true
    const fetch = handleType.value === 'add' ? addAllocateApi : editAllocateApi
    const data =
      handleType.value === 'add'
        ? {
            ...allocateForm.value,
            receivePerson: userInfo.value.userName,
            receivePersonId: userInfo.value.userId,
            receiveBranch: userInfo.value.orgName,
            receiveBranchId: userInfo.value.orgId,
            allocateOutBranch: useDictDisplay(
              orgOptions.value,
              allocateForm.value.allocateOutBranchId
            ),
            warehouseId: parseInt(allocateForm.value.warehouseId),
            receiveDate: dayjs().format('YYYY-MM-DD')
          }
        : {
            ...allocateForm.value,
            warehouseId: parseInt(allocateForm.value.warehouseId)
          }
    if (data.__displayValue__) delete data.__displayValue__
    const res = await fetch(data)
    console.log('data', data, userInfo.value.userName, userInfo.value)
    if (res.code === '0000') {
      useMsg('success', handleTag.value + '成功')
      proTableInst.value?.reload()
      allocateModalShow.value = false
    }

    confirmLoading.value = false
  }

  // 删除调拨
  const fetchDelAllocate = async (id) => {
    const res = await delAllocateApi({ id })
    if (res.code === '0000') {
      useMsg('success', '删除成功')
      proTableInst.value?.reload()
    }
  }

  return {
    fetchAllocatePage,
    fetchAddOrEditAllocate,
    fetchDelAllocate,
    confirmLoading
  }
}
